<template>
  <div class="title">班级座位表</div>
  <div class="sitTable">
    <div class="grid">
      <div v-for="(row, rowIndex) in grid" :key="rowIndex" class="row">
        <div
          v-for="(cell, colIndex) in row"
          :key="colIndex"
          :class="['cell', { active: cell.status === 1, confirmed: cell.status === 2 }]"
          @click="toggleCell(rowIndex, colIndex)"
        >
          <span v-if="cell.status === 2">{{ cell.studentName }}</span>
          <span v-else-if="cell.status === 1">{{ props.name }}</span>
        </div>
      </div>
      <div class="group-header">
        <div class="group-name">第一组</div>
        <div class="group-name">第二组</div>
        <div class="group-name">第三组</div>
        <div class="group-name">第四组</div>
        <div class="group-name">第五组</div>
      </div>
    </div>
  </div>
  <div class="button-group">
    <button @click="confirmSelection" class="confirm-button">确定</button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface Cell {
  status: number
  studentName: string
}

const props = defineProps<{
  id: number
  name: string
}>()

const emit = defineEmits(['closeDialog'])

const grid = ref<Cell[][]>(
  Array.from({ length: 7 }, () =>
    Array(10)
      .fill(null)
      .map(() => ({ status: 0, studentName: '' })),
  ),
)

const selectedCell = ref<[number, number] | null>(null)

const toggleCell = (rowIndex: number, colIndex: number) => {
  if (grid.value[rowIndex][colIndex].status === 2) return

  if (selectedCell.value) {
    const [prevRow, prevCol] = selectedCell.value
    grid.value[prevRow][prevCol].status = 0
  }
  if (
    selectedCell.value &&
    selectedCell.value[0] === rowIndex &&
    selectedCell.value[1] === colIndex
  ) {
    selectedCell.value = null
  } else {
    grid.value[rowIndex][colIndex].status = 1
    selectedCell.value = [rowIndex, colIndex]
  }
}
const fetchConfirmedCells = async () => {
  try {
    const response = await axios.get('/api/situation/getAllSituation')
    const result = response.data
    if (result.code === 0) {
      result.data.forEach(
        ({ sitRow, sitColumn, name }: { sitRow: number; sitColumn: number; name: string }) => {
          if (grid.value[sitRow] && grid.value[sitRow][sitColumn] !== undefined) {
            grid.value[sitRow][sitColumn].status = 2
            grid.value[sitRow][sitColumn].studentName = name
          }
        },
      )
    } else {
      console.error('获取数据失败:', result.message)
    }
  } catch (error) {
    console.error('请求失败:', error)
  }
}
const confirmSelection = async () => {
  if (selectedCell.value) {
    const [row, col] = selectedCell.value
    grid.value[row][col].status = 2
    await axios.post('/api/situation/update', {
      stId: props.id,
      sitRow: row,
      sitColumn: col,
    })
    ElMessage.success('选座成功！')
    selectedCell.value = null
    emit('closeDialog', false)
  }
}

// 监听 grid 数据的变化
watch(
  grid,
  (newGrid) => {
    // 这里可以执行一些操作，比如日志记录或其他处理
    console.log('Grid data updated:', newGrid)
  },
  { deep: true },
)

onMounted(() => {
  fetchConfirmedCells()
})
</script>

<style scoped lang="scss">
.title {
  margin-bottom: 18px;
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}

.grid {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.row {
  display: flex;
}

.cell {
  width: 40px;
  height: 40px;
  border: 1px solid #ccc;
  background-color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 2px;
  font-size: 12px;
  transition: background-color 0.3s;
}

.cell.active {
  background-color: lightblue;
}

.cell.confirmed {
  background-color: gray;
  color: white;
  cursor: not-allowed;
}

.group-header {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.group-name {
  width: 80px;
  text-align: center;
  font-weight: bold;
}

.selected-info {
  margin-top: 10px;
  font-weight: bold;
  text-align: center;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.confirm-button,
.change-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.confirm-button:hover,
.change-button:hover {
  background-color: #66b1ff;
}
</style>
